import { useState } from 'react';

import type { YmDataNode } from 'ym-design';
import { YmTree } from 'ym-design';

const DEFAULTTREEDATA: YmDataNode[] = [
  {
    key: '0',
    title: 'parent 0',
    children: [
      {
        key: '0-0',
        title: 'parent 0-0',
        children: [{ key: '0-0-0', title: 'leaf 0-0-0' }],
      },
      {
        key: '0-1',
        title: 'parent 0-1',
        children: [
          { key: '0-1-0', title: 'leaf 0-1-0' },
          { key: '0-1-1', title: 'leaf 0-1-1' },
          { key: '0-1-2', title: 'leaf 0-1-2', isLeaf: true },
          { key: '0-1-3', title: 'leaf 0-1-3' },
        ],
      },
    ],
  },
];

function LoadData() {
  const [treeData, setTreeData] = useState<YmDataNode[]>(DEFAULTTREEDATA);

  function loopTreeData(treeData: YmDataNode[], parentKey: string) {
    for (let i = 0; i < treeData.length; i++) {
      if (treeData[i].key === parentKey) {
        treeData[i].children = [
          { key: '0-1-0-0', title: 'leaf 0-1-0-0' },
          { key: '0-1-0-1', title: 'leaf 0-1-0-1' },
        ];
        break;
      } else if (treeData[i].children) {
        loopTreeData(treeData[i].children!, parentKey);
      }
    }
  }

  const handleLoadData = (nodeData: YmDataNode) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (nodeData.key === '0-1-0') {
          loopTreeData(treeData, '0-1-0');
          // console.log('---handleLoadData---treeData--', [...treeData])
          setTreeData([...treeData]);
          resolve(null);
        } else {
          reject();
        }
      }, 2000);
    });
  };

  return (
    <div className="tree-page">
      <div style={{ marginBottom: '30px' }}>
        <p>
          本组件没有提供受控的loadedKeys,
          loadData--promise--reject就可以多次异步加载，resolve异步加载一次
        </p>
      </div>
      <YmTree
        treeData={treeData}
        defaultExpandedKeys={['0-1-1']}
        loadData={handleLoadData}
      />
    </div>
  );
}

export default LoadData;
